<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\res\XhresArticle;
use Admin\Models\res\XhresArticlePub;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Msg;
use Modules\Power;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;

class ArticleController extends ControllerBase
{

    public static  $activityType = [1 => '校际' , 2 => '校内' , 3 => '班级'];
    public static $state = [1 => '待审批' , 2 => '审批通过' , 3 =>'审批不通过'];

    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }

    /**
     * 检查类型
     * @param $type
     * @param string $operater
     * @return bool
     * create by dale 20180327
     */
    public function checkPower($type,$operater=''){
        switch ($type){
            case 4 : $tag = 'Article_App'; break;
            case 5 : $tag = 'Article_Book';break;
            case 6 : $tag = 'Article_Plan';break;
            case 7 : $tag = 'School_RunCase';break;
            default: $tag = null;break;
        }
        if(!$tag){  //默认没有权限
            return false;
        }
        if($operater != ''){
            $tag .= '_'.ucfirst($operater); //首字母大写
        }
        return UserPower::checkUserPower($tag);
    }

    /**
     * 错误信息
     * @param bool $isView
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by dale 20180327
     */
    public function sendPowerMsg($isView=false){
        if($isView){
            return $this->sendViewError('没有权限');
        }else{
            return $this->sendErrorResponse(400,'缺少权限');
        }
    }





    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }


    public function homeAction(){

        $builder = $this->modelsManager->createBuilder()
            ->columns('a.*')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])
            ->where('a.bDelete=0')->orderBy('tLastModifyDate desc')->limit(6);
        $builder2 = clone $builder;
        $builder3 = clone $builder;
        $appMsg = $builder->andWhere('a.iArtType = 4')->getQuery()->execute()->toArray();

        $techMsg = $builder2->andWhere('a.iArtType = 5')->getQuery()->execute()->toArray();

        $planMsg = $builder3->andWhere('a.iArtType = 6')->getQuery()->execute()->toArray();

        $this->view->pick('article/home');
        Assets::importJs('js/article/myTool.js');
        Assets::importJs('js/article/home.js');

        $this->view->setVars([
            'appMsg'  => $appMsg,
            'techMsg' => $techMsg,
            'planMsg' => $planMsg,
        ]);
    }

    /**
     * 文章列表
     * created by dale 2017/10/13
     */
    public function ArticleListAction(){
        Assets::easyUI();
        Assets::importJs('js/article/articleList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/article/myTool.js');
        $this->view->pick('article/articleList');
        Template::exists('XHRes_Article', 'list') or die(Main::showMessageModal('XHRes_Article.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr =$listSearchArr= [];
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');

        $this->view->setVars(array(
            'articleList' => Template::createList('articleList', 'XHRes_Article', []),
        ));
    }

    public function getArticleAction()
    {
        $builder=$this->modelsManager->createBuilder()
                ->columns('a.iArtId,iArtType,sTargetIds,iSchoolId,tStartTime
                ,sTitle,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId')
                ->from(['a'=>'Admin\Models\res\XhresArticle'])
                ->where('a.bDelete=0');
        $data=Main::runBuilderPaginator($builder,true);

        return $this->sendJsonResponse($data);
    }


    /**
     * 保存文章
     * created by dale 2017/10/13
     */
    public function saveArticleAction(){
        $id=$this->request->getPost('iArtId','string');
        if($id!=""){
            $obj = XhresArticle::findFirst([
                'conditions'=>'bDelete=0 AND iArtId=:iArtId:',
                'bind'=>['iArtId'=>$id]
            ]);
        }else{
            $obj = new XhresArticle();
        }
        $obj->assign($this->request->getPost());
        $obj->iArtType= $this->request->getPost('iArtType','string')==''?null:$this->request->getPost('iArtType','string');
        $obj->iSchoolId= $this->request->getPost('iSchoolId','string')==''?null:$this->request->getPost('iSchoolId','string');
        if($obj->save()){
            if($id){
                return $this->sendSuccessResponse('编辑成功');
            }else{
                return $this->sendSuccessResponse('新增成功');
            }
        }else{
            if($id){
                return $this->sendSuccessResponse(500,'编辑失败');
            }else{
                return $this->sendErrorResponse(500,'新增失败');
            }
        }
    }

    /**
     * 删除文章
     * created by dale 2017/10/13
     */
    public function delArticleAction(){
        $ids = $this->request->getPost('ids','string');
        if (!$ids) {
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $ids=explode(',',$ids);
        $arts=XhresArticle::find([
            'conditions'=>'iArtId in ({ids:array})',
            'bind'  => ['ids'=>$ids],
        ]);
        foreach ($arts as $art){
            $art->bDelete = 1;
            if(!$art->save()){
                return $this->sendSuccessResponse('删除成功');
            }
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 文章表单
     * created by dale 2017/10/13
     */
    public function articleFormAction(){
        $iArtId = $this->request->getQuery('iArtId');
        Assets::easyUI();
        Assets::UMEditor();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/article/myTool.js');
        Assets::importJs('js/article/articleForm.js');
        $this->view->pick('article/articleForm');
        if($iArtId){
            $article=XhresArticle::findFirst([
                'conditions'=>'bDelete=0 AND iArtId=:iArtId:',
                'bind'=>['iArtId'=>$iArtId],
            ])->toArray();
            $article=json_encode($article);
        }else{
            $article='1';
        }

        $this->view->setVars([
            'article'=>$article,
        ]);
    }

    /**
     * 单张
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/16
     */
    public function uploadImgsAction(){
        $files=$this->request->getUploadedFiles();
        if(isset($files)){
            $file=$files[0];
        }else{
            return $this->sendErrorResponse(500,'没有上传文件');
        }
        try{
//            $savePath = Main::getConfigByName('hrm')['saveExcel'];
//            if (!is_dir($savePath)) {
//                mkdir($savePath, 0777, true) or die($savePath . '创建失败');
//            }
            $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();

            $filePath = TEMP_PATH . '/'.$fileName;
            $file->moveTo($filePath);
            $url = Main::uploadFileToOSS($filePath,'img');
            unlink($filePath);
        }catch (\Exception $e){
            echo $e->getMessage();die();
        }

        $returnArray=[
            "originalName" => $file->getName(),
            "name" => $fileName,
            "url" =>  $url,//不能少
            "size" => $file->getSize(),
            "type" =>$file->getExtension() ,
            "state" => 'SUCCESS' //不能少
        ];

        return $this->sendJsonResponse($returnArray);
    }

    /**
     * 信息列表
     *
     * created by dale 2017/10/28
     */
    public function msgListAction(){
        $type     = $this->request->getQuery('type');
        $openType = $this->request->getQuery('openType');
        if(!$this->checkPower($type)){
            return $this->sendPowerMsg(true);
        }
        Assets::easyUI();
        Assets::importJs('js/article/msgList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/article/myTool.js');
        $this->view->pick('article/msgList');
        Template::exists('XHRes_Msg', 'list') or die(Main::showMessageModal('XHRes_Msg.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr =$listSearchArr= [];
        if($type==4&&UserPower::checkUserPower('Article_App_Add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }else if($type==5&&UserPower::checkUserPower('Article_Book_Add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }else if($type==6 && UserPower::checkUserPower('Article_Plan_Add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }else if($type==7 && UserPower::checkUserPower('School_RunCase_Add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if($type==4&&UserPower::checkUserPower('Article_App_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }else if($type==5&&UserPower::checkUserPower('Article_Book_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }else if($type==6 && UserPower::checkUserPower('Article_Plan_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }else if($type==7 && UserPower::checkUserPower('School_RunCase_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }

        $tableConfig = [];
        if ($type==7){
            if($this->checkPower($type,'shareCheck')){
                if(UserPower::checkUserPower('School_RunCase_Grade')){
                    $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_exmenu', 'text' => '考核打分', 'class' => 'bt_list_menu');
                }else{
                    $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_exmenu', 'text' => '考核打分', 'class' => 'bt_list_menu','style' => 'display:none');
                }

                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_share', 'text' => '分享审核', 'icon' => 'fa-share');
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeShare', 'text' => '查看分享审核', 'icon' => 'fa-eye');
            }
            if ( Power::exist('School_RunCase_EvalLevel')){
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_levelMenu', 'text' => '案例评级', 'class' => 'bt_list_menu');
            }
            $tableConfig['tableAttr']['title'] = '运营案例';
            $dep = XhhrmDepart::findFirst([
                'columns'    => 'iDepId,sDepName',
                'conditions' => 'bDelete = 0 AND sTag = :sTag:',
                'bind'       => ['sTag'=>'XHYYB']
            ]);
            $area = XhhrmDepart::find([
                'columns'    => 'iDepId,sDepName,iParentId',
                'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
                'bind'       => ['iParentId'=>$dep->iDepId],
            ]);
            $area = array_column($area->toArray(),'sDepName','iDepId');
            $area[''] = '--请选择区--';
            $city[''] = '--请选择市--';
            $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_area', 'data'=>$area,'default'=>'');
            $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_city', 'data'=>$city,'default'=>'');
        }
//        $listSearchArr[] = array('type' => 'select', 'id' => 'select_school', 'data' => $this->getSearchEnum(XhschoolInfo::getSchoolArray(),'请选择学校'), 'default' => '','style'=> 'width:200px');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $tableConfig['searchToolbar'] = Template::createSearchToolBar($listSearchArr, !!$listButtonArr);
        $tableConfig['buttonToolbar'] = Template::createButtonToolBar($listButtonArr);
        if($openType){
            $tableConfig = [];
        }
        $this->view->setVars(array(
            'msgList' => Template::createList('msgList', 'XHRes_Msg',$tableConfig),
        ));
    }

    /**
     * 获取信息表单
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/10/28
     */
    public function getMsgAction(){
        $type = $this->request->getPost('type');
        $schoolId = $this->request->getPost('schoolId');
        $userId   = $this->request->getPost('userId');
        $openType = $this->request->getPost('openType');
        $key      = $this->request->getPost('key');
        $city     = $this->request->getPost('city');
        $area     = $this->request->getPost('area');
        $builder=$this->modelsManager->createBuilder()
            ->columns('a.iArtId,iArtType,sTargetIds,iSchoolId,tStartTime,a.sExMonth,a.bExcellent,a.iLevel,a.bLock
                ,sTitle,iUserId,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])
            ->where('a.bDelete=0')->orderBy('tLastModifyDate desc');
//        if( Main::getLoginUserInfo('logonName') != 'admin' ){
//            $builder->andWhere('a.iCreateUserId = :iCreateUserId:',array('iCreateUserId'=>$iUserId));
//        }

        if ($schoolId) {
            $builder->andWhere('iSchoolId = :iSchoolId:',['iSchoolId' => $schoolId]);
        }
        if ($userId) {
            $builder->andWhere('iUserId = :iUserId:',['iUserId'=>$userId]);
        }
        if ($key) {
            $machIds = School::searchSchool($key);
            if ($machIds) {
                $builder->andWhere('sTitle like :key: or iSchoolId in ({ids:array}) ' , ['key' => '%'.$key.'%' , 'ids' => $machIds]);
            } else {
                $builder->andWhere('sTitle like :key:  ' , ['key' => '%'.$key.'%' ]);
            }
        }
        if (in_array($type, [7])){
            $staff = false;
            if ($city || $area) {
                $depId = $city ?: $area;
                $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            }
            $schoolIds =  School::getMergePower( $staff ? $staff['userId'] : null , false);
            if ($schoolIds !== true) {
                if(count($schoolIds) > 0){
                    $builder->andWhere('a.iSchoolId in ({schoolIds:array})' , ['schoolIds' => $schoolIds]);
                }else{
                    return $this->sendErrorResponse(500 , '没有学校权限');
                }
            }
        }
        $builder->andWhere('iArtType=:iArtType:',array('iArtType' => $type));
        $data=Main::runBuilderPaginator($builder,true);

        Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
        $schools = XhschoolInfo::getSchoolArray();
        foreach ($data['rows'] as &$row){
            if($row['iArtType'] == 7 ){
                if($row['iLevel'] == 2 ){
                    $row['sTitle'] = '<font style="color:#FFCC33; " >'.$row['sTitle'].'</font>';
                }else if($row['iLevel'] == 3 ){
                    $row['sTitle'] = '<font style="color: darkmagenta">'.$row['sTitle'].'</font>';
                }
            }
            $row['sSchoolName'] = $schools[$row['iSchoolId']];
        }
        unset($row);
        return $this->sendJsonResponse($data);
    }

    /**
     * 信息表单
     *
     * created by dale 2017/10/28
     */
    public function msgFormAction(){
        $iArtId=$this->request->getQuery('iArtId');
        Assets::easyUI();
        Assets::UMEditor();
        Assets::select2();
        Assets::datetimePicker();
        Assets::importMainJs('assets/umeditor/xh/xh.accessory.js');
        Assets::importMainCss('assets/umeditor/xh/xh.accessory.css');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/article/myTool.js');
        Assets::importJs('js/article/msgForm.js');
        $this->view->pick('article/articleForm');
        if($iArtId){
            $article=XhresArticle::findFirst([
                'conditions'=>'bDelete=0 AND iArtId=:iArtId:',
                'bind'=>['iArtId'=>$iArtId],
            ])->toArray();
            if($article['iCreateUserId'] != Main::getLoginUserInfo('userId') && Main::getLoginUserInfo('logonName') != 'admin'){
               return $this->response->redirect('mobile/home/msgDetail?iArtId='.$iArtId);
            }
            $article=json_encode($article);
        }else{
            $article='1';
        }
        $this->view->setVars([
            'article' => $article,
        ]);
    }

    /**
     * 保存文章
     *
     * created by dale 2017/10/13
     * modify by dale 20180504 新增type 8 百分网tag
     */
    public function saveMsgAction(){
        $id=$this->request->getPost('iArtId','string');
        $type = $this->request->getQuery('iArtType') ?: $this->request->getPost('iArtType');

        if($id){
            $operator = 'edit';
        }else{
            $operator = 'add';
        }
        if( $type != 8  && !$this->checkPower($type,$operator)){ //如果为8跳过权限验证
            return $this->sendPowerMsg();
        }
        if($id != ""){
            $obj = XhresArticle::findFirst([
                'conditions'=>'bDelete=0 AND iArtId=:iArtId:',
                'bind'=>['iArtId'=>$id]
            ]);
        }else{
            $obj = new XhresArticle();
        }
        $obj->assign($this->request->getPost());
        if($type == 8){
            $tag = $this->request->getPost('sTag','string');
            $obj->sTag = strtoupper($tag);  //标识符大写
            if ($this->checkTag($obj->sTag,$obj->iArtId)) {
                return $this->sendErrorResponse(400,'标识已存在');
            }
        }
        $obj->iArtType= $this->request->getPost('iArtType','string')==''?null:$this->request->getPost('iArtType','string');
        $obj->iSchoolId= $this->request->getPost('iSchoolId','string')==''?null:$this->request->getPost('iSchoolId','string');
        if($obj->save()){
            if($id){
                return $this->sendSuccessResponse('编辑成功');
            }else{
                return $this->sendSuccessResponse('新增成功');
            }
        }else{
            if($id){
                return $this->sendSuccessResponse(500,'编辑失败');
            }else{
                return $this->sendErrorResponse(500,'新增失败');
            }
        }
    }

    public function checkTag($tag,$id = null ){
        $art = XhresArticle::findFirst([
            'columns'    => 'sTag , iArtId',
            'conditions' => 'bDelete = 0 and sTag = :sTag:',
            'bind'       => ['sTag' => $tag]
        ]);
        //未创建时,找到tag
        if ( !$id && $art ) {
            return true;
        } else if ($art && $id && $art->iArtId != $id) {//已创建时
            return true;
        }
        return false;
    }

    /**
     * 删除文章
     *
     *
     * created by dale 2017/10/13
     */
    public function delMsgAction(){
        $ids=$this->request->getPost('ids','string') or die('缺少参数');
        $type = $this->request->getPost('type');
        if(!$this->checkPower($type,'del')){
            return $this->sendPowerMsg();
        }
        $ids=explode(',',$ids);
        $arts=XhresArticle::find([
            'conditions'=>'iArtId in ({ids:array})',
            'bind'  => ['ids'=>$ids],
        ]);
        foreach ($arts as $art){
            $art->bDelete = 1;
            if(!$art->save()){
                return $this->sendSuccessResponse('删除成功');
            }
        }
        return $this->sendSuccessResponse('删除成功');
    }


    public function getTchAction(){
       $schoolId = $this->request->getPost('schoolId');
       if(!$schoolId){
           return $this->sendErrorResponse(400,'缺少参数');
       }
       $users = XhsysUser::find([
           'columns'    => 'iUserId,sUserName',
//           'conditions' => 'bDelete = 0 AND iUserType = 4 AND iSchoolId = :iSchoolId: AND bCompany = 0 AND bDisable = 0 AND bHistory = 0 ',
           'conditions' => 'bDelete = 0 AND iUserType = 4 AND iSchoolId = :iSchoolId: AND bDisable = 0 AND bHistory = 0 ',
           'bind'       => ['iSchoolId' => $schoolId]
       ])->toArray();
       $users = array_column($users,'sUserName','iUserId');
       return $this->sendJsonResponse($users);
    }


    /**
     * 活动列表
     *
     * create by xjq 20180604
     */
    public function activityListAction(){
        $schoolId = $this->request->get('schoolId');
        if (!UserPower::checkUserPower('School_Activity')) {
            return $this->sendViewError('没有权限');
        }
        Assets::easyUI();
        Assets::importJs('js/article/activityList.js');
        $this->view->pick('article/activityList');
        Template::exists('XHRes_Activity', 'list') or die(Main::showMessageModal('XHRes_Activity.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr =$listSearchArr= [];
        if (UserPower::checkUserPower('School_Activity_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('School_Activity_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('School_Activity_Check')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_checkMenu', 'text' => '审核', 'class' => 'bt_list_menu');
        }
        if (! $schoolId) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_stat', 'text' => '统计', 'icon' => 'fa fa-tachometer fa-lg');
        }
        $dep = XhhrmDepart::findFirst([
            'columns'    => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND sTag = :sTag:',
            'bind'       => ['sTag'=>'XHYYB']
        ]);
        $area = XhhrmDepart::find([
            'columns'    => 'iDepId,sDepName,iParentId',
            'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
            'bind'       => ['iParentId'=>$dep->iDepId],
        ]);
        $area = array_column($area->toArray(),'sDepName','iDepId');
        $area[''] = '--请选择区--';
        $city[''] = '--请选择市--';
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_area', 'data'=>$area,'default'=>'');
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_city', 'data'=>$city,'default'=>'');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_tag', 'data' => $this->getSearchEnum(self::$activityType,'请选择类型'), 'default' => '');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $this->getSearchEnum(self::$state,'请选择状态'), 'default' => '');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_school', 'data' => $this->getSearchEnum(XhschoolInfo::getSchoolArray(),'请选择学校'), 'default' => '','style'=> 'width:200px');
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_timeType', 'data' => [
            'a.tStartTime' => '活动开始时间',
            'a.tEndTime' => '活动结束时间',
            'a.tCreateDate' => '创建时间',
            'a.tLastModifyDate' => '修改时间'
        ],'default'=>'a.tStartTime');

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_startTime', 'label' => ' ',
            'class'=>'easyui-datebox','style'=>'width:100px !important ;');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search_endTime', 'label' => ' ~',
            'class'=>'easyui-datebox','style'=>'width:100px !important ;');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'List'       => Template::createList('list', 'XHRes_Activity', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ));
    }

    private function getSearchEnum($arr,$placeHolder){
        $arr[''] = $placeHolder;
        return $arr;
    }

    /**
     * 获取
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180604
     */
    public function getActivityAction(){
        if (!UserPower::checkUserPower('School_Activity')) {
            return $this->sendErrorResponse(401 , '没有权限');
        }
        $schoolId = $this->request->getPost('schoolId' , 'int');
        $key      = $this->request->getPost('key' , 'string');
        $order    = $this->request->getPost('order','string');
        $sort     = $this->request->getPost('sort' , 'string');
        $tag      = $this->request->getPost('tag'  , 'string');
        $state    = $this->request->getPost('state' , 'string');
        $area     = $this->request->getPost('area' , 'string');
        $city     = $this->request->getPost('city' , 'string');
        $timeType = $this->request->getPost('timeType', 'string');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime   = $this->request->getPost('endTime', 'string');
        $builder  = $this->modelsManager->createBuilder()
            ->columns('a.*')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])
            ->leftJoin('Admin\\Models\\school\\XhschoolInfo','a.iSchoolId = s.iSchoolId','s')
            ->where('a.bDelete=0')->orderBy('a.tLastModifyDate desc');
        $builder->andWhere('a.iArtType = :iArtType:',array('iArtType'=> 9 ));
        if ($schoolId) {
            $builder->andWhere('a.iSchoolId = :iSchoolId:',['iSchoolId' => $schoolId]);
        }
        if ($key) {
            $machIds = School::searchSchool($key);
            if ($machIds) {
                $builder->andWhere('a.sTitle like :key: or a.iSchoolId in ({ids:array}) ' , ['key' => '%'.$key.'%' , 'ids' => $machIds]);
            } else {
                $builder->andWhere('a.sTitle like :key:  ' , ['key' => '%'.$key.'%' ]);
            }
        }
        if ($timeType && $startTime && $endTime) {
            $builder->andWhere(" DATE_FORMAT(".$timeType.",'%Y-%m-%d') >= :startTime: 
            and  DATE_FORMAT(".$timeType.",'%Y-%m-%d') <= :endTime:",['startTime' => $startTime, 'endTime' => $endTime]
            );
        }
        $staff = false;
        if ($city || $area) {
            $depId = $city ?: $area;
            $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
        }
        $schoolIds =  School::getMergePower( $staff ? $staff['userId'] : null , false);
        if ($schoolIds !== true) {
            if(count($schoolIds) > 0){
                $builder->andWhere('a.iSchoolId in ({schoolIds:array})' , ['schoolIds' => $schoolIds]);
            }else{
                return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
//                return $this->sendDataGridError('没有学校权限' , $schoolIds);
            }
        }

        if ($tag) {
            $builder->andWhere( 'a.sTag = :sTag:' , ['sTag' => $tag]);
        }
        if ($state) {
            $builder->andWhere( 'a.iState = :state:' , ['state' => $state]);
        }
        if ($order && $sort) {
            $sort = $sort == 'sSchoolName' ? 'iSchoolId' : $sort;
            $sort = $sort == 'iActType' ? 'sTag' : $sort;
            $builder->orderBy( " a.{$sort}  {$order} ");
        }

//        if (!User::isAdmin()) {
//            $conditionsArr = [
//                'conditions' => 'iCreateUserId = :nowUser:',
//                'bind'       => ['nowUser' => Main::getLoginUserInfo('userId')]
//            ];
//            if(User::getExtraPower('dep','schoolActivity',null,true)){ //有扩展权限
//                $userIds = $this->extraPower('schoolActivity');
//                if (!is_bool($userIds)){
//                    $conditionsArr['conditions'] .= " or  iCreateUserId in ({userIds:array}) ";
//                    $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('userIds' => $userIds));
//                }
//            }
//            $builder->andWhere($conditionsArr['conditions'] , $conditionsArr['bind']);
//        }

        $data = Main::runBuilderPage($builder,['iState'=>self::$state]);
        $schools = XhschoolInfo::getSchoolArray();
        foreach ($data['rows'] as $index => &$row ){
            $row['iActType'] = self::$activityType[$row['sTag']];
            $row['sSchoolName'] = $schools[$row['iSchoolId']];
        }
        unset($row);
        Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 活动表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180604
     */
    public function actFormAction(){
        $iArtId=$this->request->getQuery('iArtId');
        Assets::easyUI();
        Assets::UMEditor();
        Assets::select2();
        Assets::datetimePicker();
        Assets::importMainJs('assets/umeditor/xh/xh.accessory.js');
        Assets::importMainCss('assets/umeditor/xh/xh.accessory.css');
        Assets::importJs('js/article/actForm.js');
        $this->view->pick('article/actForm');
        $this->view->setVar('iActType' , self::$activityType);
        if ($iArtId) {
            $article=XhresArticle::findFirst([
                'conditions'=>'bDelete=0 AND iArtId=:iArtId:',
                'bind'=>['iArtId'=>$iArtId],
            ])->toArray();
            if($article['iCreateUserId'] != Main::getLoginUserInfo('userId') && Main::getLoginUserInfo('logonName') != 'admin'){
                return $this->response->redirect('mobile/home/msgDetail?iArtId='.$iArtId);
            }
            $article = json_encode($article);
            $this->view->setVar('info' , $article);
        }
        //classes
        $schoolId = $this->request->getQuery('schoolId');
        $sql = "select sAdClsName from XHSys_User where iUserType = 1 and bDelete = 0 and bHistory = 0 and bDisable = 0 and iSchoolId={$schoolId}  group by sAdClsName";
        $arr['classes'] = array_filter(array_column($this->db->fetchAll($sql) , 'sAdClsName','sAdClsName' ));
        $arr['schools'] = User::getSchoolPower(true);
        $arr['grades']  = XhsysEnum::getEnumByNodeName('年级');
        $this->view->setVar('targets'  , $arr);
        $this->view->setVar('schoolId' , $this->request->getQuery('schoolId'));
        $this->view->setVar('subjects' , XhsysEnum::getEnumByNodeName('学科') );
        if ($schoolId){
            $sql = "select a.iUserId,a.sName from XHCust_Contact as a left join XHCust_Info as i on i.iCUId = a.iCUId where a.bDelete = 0  and a.iUserId is not null and i.iSchoolId = {$schoolId} ";
            $contact = array_column($this->db->fetchAll($sql),'sName','iUserId');
            $sql = "select iUserId,sUserName from XHSys_User where bDelete= 0 and bDisable = 0 and bHistory = 0 and iUserType = 4 and iSchoolId = {$schoolId} ";
            $teacher = array_column($this->db->fetchAll($sql) ,'sUserName','iUserId');
            $users = $contact + $teacher;
            $this->view->setVar('users' , $users);
        }
    }


    /**
     * 保存活动
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180605
     */
    public function saveActivityAction(){
        $data = $this->request->getPost();
        try{
            $targets = $this->request->getPost('sTargetIds');
            $subject = $this->request->getPost('sSubject');
            if (isset($data['iArtId']) && $data['iArtId']) {
                $obj = XhresArticle::findFirst($data['iArtId']);
            } else {
                $obj = new XhresArticle();
            }
            unset($data['sTargetIds']);
            unset($data['sSubject']);
            $obj->assign($data);
            $obj->sTargetIds = count($targets) > 0 ? implode(',' , $targets) :null;
            $obj->sSubject   = count($subject) > 0 ? implode(',' , $subject) :null;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            if ($obj->iState == 3 && $obj->iCreateUserId == $obj->iLastModifyUserId) {
                $obj->iState = 1;
                if (!$obj->save()) {
                    return $this->sendErrorResponse(500, '保存失败');
                }
            }
//            if ($obj->iState == 1) {
//                Msg::insertWPageUserMsg(
//                    $obj->sTitle,
//                    'school_activity',
//                    $obj->i
//                )
//            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 删除活动
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180605
     */
    public function delActivityAction()
    {
        try{
            $id = $this->request->getPost('id','string');
            $obj = XhresArticle::findFirst($id);
            if (!User::isAdmin() && $obj->iCreateUserId != Main::getLoginUserInfo('userId')
                && !Power::exist('School_Activity_Check')) {
                return $this->sendErrorResponse(401 , '没有权限');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse( 500 , $e->getMessage());
        }
    }


    /**
     * 审核表单
     *
     * @param $flag
     *
     * create by xjq 20180607
     */
    public function checkFormAction($flag){
        $this->view->pick('article/checkForm');
        $this->view->setVars([
            'flag'   => $flag,
            'iArtId' => $this->request->getQuery('iArtId'),
        ]);
    }

    /**
     * 审核
     *
     * create by xjq 20180607
     */
    public function checkAction(){
        $flag   = $this->request->getPost('flag','string');
        $iArtId = $this->request->getPost('iArtId','int');
        $obj = XhresArticle::findFirst($iArtId);
        if ($flag == 'true') {
            $obj->iState = 2;
        }else if ($flag == 'false') {
            $obj->iState = 3;
        }
        $obj->mDesc = $this->request->getPost('mDesc');
        if (!$obj->save()) {
            return $this->sendErrorResponse(500 , '保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }



    /**
     * 文件上传
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180604
     */
    public function fileUploadAction(){
        if($this->request->hasFiles()) {
            $parseConfig = Main::getConfigByName('appParse');
            $tempPath = $parseConfig['tempPath'];
            $file = $this->request->getUploadedFiles()[0];
            try{
                $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
                $filePath = $tempPath . '/'.$fileName;
                $file->moveTo($filePath);
                $url = Main::uploadFileToOSS($filePath,'file');
                unlink($filePath);
                $returnArray=[
                    "originalName" => $file->getName(),
                    "name" => $fileName,
                    "url" =>  $url,//不能少
                    "size" => $file->getSize(),
                    "type" =>$file->getExtension() ,
                    "state" => 'SUCCESS', //不能少
                    'code'  => 200
                ];
                return $this->sendJsonResponse($returnArray);
            }catch (\Exception $e){
                return $this->sendErrorResponse(500 , $e->getMessage() );
            }
        }else{
            return $this->sendErrorResponse(500 ,'没有文件上传');
        }
    }

    /**
     * 获取运营部区长及以上的人员id,以及名称
     *
     * create by xjq 20180615
     */
    public function getRunChargeIdFromAreaAction(){
        $depId = XhhrmDepart::findFirst([
            'columns' => 'iDepId',
            'conditions' => 'bDelete = 0 and sTag = :sTag:',
            'bind'       => ['sTag' => 'XHYYB']
        ])->toArray();
        $depId = $depId['iDepId'];
        $areaId = XhhrmDepart::find([
            'columns' => 'iDepId',
            'conditions' => 'bDelete = 0 and iParentId = :iParentId:',
            'bind'       => ['iParentId' => $depId],
        ])->toArray();

        $areaId = array_column($areaId , 'iDepId');
        $areaId[]= $depId;
        foreach ($areaId as $depId){
            $arr[] = " CONCAT(',',sChargeDeps,',') like '%,{$depId},%' ";
        }

        $sql = "select iUserId , sStaffName from XHHrm_Staff where bDelete = 0 AND (" . implode( ' OR ' , $arr ) . " ) " ;
        $users = $this->db->fetchAll($sql);
        return array_column($users , 'sStaffName','iUserId');
    }

    /**
     * 改变案例等级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180615
     */
    public function changeLevelAction(){
        try{
            $id    = $this->request->getPost('id' , 'int');
            $level = $this->request->getPost('level' , 'int');
            $week = XhresArticle::findFirst($id);
            if (!$week) {
                return $this->sendErrorResponse(500 , '缺少参数');
            }
            $userId = Main::getLoginUserInfo('userId');
            if(!User::isAdmin() && !in_array($userId , array_keys($this->getRunChargeIdFromAreaAction())) && $week->bLock == 1 ){
                return $this->sendErrorResponse(500 ,'已经锁定，无法评级');
            }
            if(User::isAdmin() || in_array($userId , array_keys($this->getRunChargeIdFromAreaAction())) ){
                $week->bLock = 1;
            }
            $week->iLevel = $level;
            if (!$week->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    public function caseListAction(){
        Assets::easyUI();
        Assets::importJs('js/article/caseList.js');
        $this->view->pick('article/caseList');
        Template::exists('XHRes_Msg', 'list') or die(Main::showMessageModal('XHRes_Msg.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr =$listSearchArr= [];
        $tableConfig['tableAttr']['title'] = '案例库';
        $dep = XhhrmDepart::findFirst([
            'columns'    => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND sTag = :sTag:',
            'bind'       => ['sTag'=>'XHYYB']
        ]);

        $area = XhhrmDepart::find([
            'columns'    => 'iDepId,sDepName,iParentId',
            'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
            'bind'       => ['iParentId'=>$dep->iDepId],
        ]);
        $area = array_column($area->toArray(),'sDepName','iDepId');
        $area[''] = '--请选择区--';
        $city[''] = '--请选择市--';
        $level = ['' => '全部' , 1 => '一般' , 2 => '良好', 3 => '优秀'];
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_level', 'data'=>$level,'default'=>3);
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_area', 'data'=>$area,'default'=>'');
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_city', 'data'=>$city,'default'=>'');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $tableConfig['searchToolbar'] = Template::createSearchToolBar($listSearchArr, !!$listButtonArr);
        $tableConfig['buttonToolbar'] = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars(array(
            'caseList' => Template::createList('list', 'XHRes_Msg',$tableConfig),
        ));
    }

    /**
     * 获取案例池
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180615
     */
    public function getCaseAction(){
        $key      = $this->request->getPost('key','string');
        $city     = $this->request->getPost('city','string');
        $area     = $this->request->getPost('area','string');
        $level    = $this->request->getPost('level' , 'string');
        $builder=$this->modelsManager->createBuilder()
            ->columns('a.iArtId,iArtType,sTargetIds,iSchoolId,tStartTime,a.sExMonth,a.bExcellent,a.iLevel,a.bLock
                ,sTitle,iUserId,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId')
            ->from(['a'=>'Admin\Models\res\XhresArticle'])
            ->where('a.bDelete=0 and a.iArtType = 7')->orderBy('tLastModifyDate desc');
        if ($key) {
            $machIds = School::searchSchool($key);
            if ($machIds) {
                $builder->andWhere('sTitle like :key: or iSchoolId in ({ids:array}) ' , ['key' => '%'.$key.'%' , 'ids' => $machIds]);
            } else {
                $builder->andWhere('sTitle like :key:  ' , ['key' => '%'.$key.'%' ]);
            }
        }
        if ($level) {
            $builder->andWhere( 'iLevel = :iLevel:' , ['iLevel' => $level]);
        }
        $staff = false;
        if ($city || $area) {
            $depId = $city ?: $area;
            $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
        }
        $schoolIds =  School::getPower( false , $staff ? $staff['userId'] : null );
        if ($schoolIds !== true) {
            if(count($schoolIds) > 0){
                $builder->andWhere('a.iSchoolId in ({schoolIds:array})' , ['schoolIds' => $schoolIds]);
            }else{
                return $this->sendErrorResponse(500 , '没有学校权限');
            }
        }
        $data=Main::runBuilderPaginator($builder,true);
        Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
        $schools = XhschoolInfo::getSchoolArray();
        foreach ($data['rows'] as &$row){
            if($row['iLevel'] == 2 ){
                $row['sTitle'] = '<font style="color:#FFCC33; " >'.$row['sTitle'].'</font>';
            }else if($row['iLevel'] == 3 ){
                $row['sTitle'] = '<font style="color: darkmagenta">'.$row['sTitle'].'</font>';
            }
            $row['sSchoolName'] = $schools[$row['iSchoolId']];
        }
        unset($row);
        return $this->sendJsonResponse($data);
    }


    /**
     * 智通新闻
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180815
     */
    public function ztNewsListAction(){
        $this->view->setTemplateBefore('listForm');
        if (!Power::exist('Article_ZTNews')) {
            return $this->sendViewError('缺少权限');
        }
//        $this->view->pick('article/ztNewsList');
        Assets::easyUI();
        Assets::importJs('js/article/ztNewsList.js');
        Template::exists('Article_ztNews', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (Power::exist('Article_ZTNews_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (Power::exist('Article_ZTNews_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (Power::exist('Article_ZTNews_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_top', 'text' => '置顶', 'icon' => 'fa-pencil');
        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'Article_ztNews', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取新闻内容
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180816
     */
    public function getNewsAction(){
        try {
            if (!Power::exist('Article_ZTNews')) {
                return $this->sendErrorResponse(400, '缺少权限');
            }
            $key = $this->request->getPost('key', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->columns('a.iArtId,a.iArtType,a.sTitle,a.mText,p.sCoverUrl,p.sCoverMobile,p.bShow,p.bTop,p.iColumn,p.iPublicTime,a.tCreateDate,a.iCreateUserId,a.tLastModifyDate,a.iLastModifyUserId')
                ->from(['p' => 'Admin\Models\res\XhresArticlePub'])
                ->leftJoin( 'Admin\Models\res\XhresArticle', 'a.iArtId = p.iArtId', 'a')
                ->where('a.bDelete = 0 and a.iArtType = 10 ')
                ->orderBy('a.tCreateDate desc');
            if ($key) {
                $builder->andWhere('sTitle like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder,[
                'bShow' => [0 => '否', 1 => '是'],
                'bTop'  => [0 => '否', 1 => '是'],
                'iColumn' => self::$newColumns
            ]);
            foreach ($data['rows'] as &$row) {
                $row['iPublicTime'] = date('Y-m-d', $row['iPublicTime']);
            }
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    public static $newColumns = [1 => '学海新闻', 2  => '活动资讯', 3 => '媒体报道'];

    /**
     * 新闻表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180816
     */
    public function newsFormAction(){
        try {
            Assets::easyUI();
            Assets::UMEditor();
            Assets::select2();
            Assets::importJs('js/article/newsForm.js');
            $this->view->pick('article/newsForm');
            $iArtId = $this->request->getQuery('iArtId');
            if ($iArtId) {
                $sql = "select a.sTitle,a.mText,a.iArtType,a.iCreateUserId,p.* from XHRes_Article as a LEFT JOIN  XHRes_ArticlePub as p ON p.iArtId = a.iArtId where a.bDelete = 0 and a.iArtId = {$iArtId} ";
                $info =  $this->db->fetchOne($sql);
                $info['iPublicTime'] = date('Y-m-d', $info['iPublicTime']);
//                if (!User::isAdmin() && !(Power::exist('Article_ZTNews_Edit') && Main::getLoginUserInfo('userId') == $info['iCreateUserId'])) {
//                    $this->view->setVar('bindHind', "<script>parent.$('#bt_modal_confirm').hide()</script>");
//                }
                $this->view->setVar('info',$info);
            }
            return $this->view->setVars([
                'newsColumn' => self::$newColumns
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }


    /**
     * 保存新闻上传
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180816
     */
    public function saveNewsAction(){
        try {
            $this->db->begin();
            $id = $this->request->getPost('iArtId', 'int');
            $postData = $this->request->getPost();
            if ($id) {
                if (!Power::exist('Article_ZTNews_Edit')) {
                    return $this->sendErrorResponse(403, '缺少权限');
                }
                $obj = XhresArticle::findFirst($id);
                $expend = XhresArticlePub::findFirst($id);
            } else {
                if (!Power::exist('Article_ZTNews_Add')) {
                    return $this->sendErrorResponse(403, '缺少权限');
                }
                $obj = new XhresArticle();
                $expend = new XhresArticlePub();
            }
            $obj->sTitle = $postData['sTitle'];
            $obj->iArtType = 10;
            $obj->mText  = $postData['mText'];
            if (!$obj->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存失败');
            }
            $expend->iArtId  = $obj->iArtId;
            $expend->iColumn = $postData['iColumn'];
            $expend->iPublicTime = strtotime($postData['iPublicTime']);
            if ($this->request->hasFiles()) { //有图片上传
                $files = $this->request->getUploadedFiles();
                foreach ($files as $file){
                    $fileName = $file->getName();
                    if (!$fileName) {
                        continue;
                    }
                    if ($file->getSize()/1024 > 500) {
                        throw new XhException('上传大小大于500k');
                    }
                    $fullPath = TEMP_PATH . $fileName;
                    if (!is_writable(TEMP_PATH)) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500 , TEMP_PATH . '缓存无写入权限');
                    }
                    $file->moveTo($fullPath);
                    $url = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
                    @unlink($fullPath);
                    if ($file->getKey() == 'pcCover'){
                        $expend->sCoverUrl = $url;
                    } else if ($file->getKey() == 'mobileCover'){
                        $expend->sCoverMobile = $url;
                    } else {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '未知文件键值');
                    }
                }
            }
            if (!$expend->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 置顶文章
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180816
     */
    public function changeTopAction(){
        try {
            if (!Power::exist('Article_ZTNews_Edit')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            $this->db->begin();
            $id = $this->request->getPost('id','int');
            $nowTop = XhresArticlePub::findFirst([
                'conditions' => 'bTop = 1'
            ]);
            if ($nowTop) {
                if ($nowTop->iArtId == $id) {
                    return $this->sendErrorResponse(500,'当前新闻已经置顶');
                }
                $nowTop->bTop = 0;
                if (!$nowTop->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '置顶失败');
                }
            }
            $obj = XhresArticlePub::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500, '未找到需要置顶的文章');
            }
            if (!$obj->sCoverMobile || !$obj->sCoverUrl) {
                return $this->sendErrorResponse(500, '封面或者手机端图片没有上传');
            }
            $obj->bTop = 1;
            if (!$obj->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500, '置顶失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('置顶成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 数据转移
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180828
     */
//    public function moveToNewDbAction()
//    {
//        try {
//            $this->db->begin();
//            $sql = "select post_date,post_title,post_content,post_modified  from zjxhedu.wp_posts WHERE post_status = 'publish' and ping_status='open' and post_modified > '2018-08-03 05:18:00'  ";
//            $data = $this->db->fetchAll($sql);
//            foreach ($data as $row) {
//                $obj = new XhresArticle();
//                $obj->sTitle = $row['post_title'];
//                $obj->iArtType = 10;
//                $obj->mText = str_replace(["\r\n", "\r", "\n"], '<br />', $row['post_content']);
//                $obj->mText = str_replace('电子书包', '智通云', $obj->mText);
//                $obj->tCreateDate = $row['post_date'];
//                $obj->tLastModifyDate = $row['post_modified'];
//                if (!$obj->save()) {
//                    $this->db->rollback();
//                    return $this->sendErrorResponse(500, '保存失败');
//                }
//                $pub = new XhresArticlePub();
//                $pub->iArtId = $obj->iArtId;
//                $pub->iPublicTime = strtotime($row['post_date']);
//                if (!$pub->save()) {
//                    $this->db->rollback();
//                    return $this->sendErrorResponse(500, '保存失败');
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('转移成功');
//        } catch (\Exception $e) {
//            var_dump(json_encode($data));
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//    }

//    public function moveNewIdAction()
//    {
//        try {
//            $this->db->begin();
//            $articles = XhresArticle::find([
//                'conditions' => 'iArtType = 10',
//            ])->toArray();
//            $articlePubs = XhresArticlePub::find([
//                'conditions' => 'iArtId > 0'
//            ])->toArray();
//            $articlePubs = array_column($articlePubs, null, 'iArtId');
////            var_dump($articles,$articlePubs);die;
////            $sql = "select post_date,post_title,post_content,post_modified  from zjxhedu.wp_posts WHERE post_status = 'publish' and ping_status='open' ";
////            $data = $this->db->fetchAll($sql);
//            foreach ($articles as $row) {
//                $obj = new XhresArticle();
//                $obj->assign($row);
//                $obj->iArtId = null;
//                if (!$obj->save()) {
//                    $this->db->rollback();
//                    return $this->sendErrorResponse(500, '保存失败');
//                }
//                $pub = new XhresArticlePub();
//                $pub->assign($articlePubs[$row['iArtId']]);
//                $pub->iArtId = $obj->iArtId;
//                if (!$pub->save()) {
//                    $this->db->rollback();
//                    return $this->sendErrorResponse(500, '保存失败');
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('转移成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//    }


    /**
     * 替换图片
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180828
     */
//    public function replaceImgAction(){
//        try {
//
//            $objArr = XhresArticle::find([
//                'conditions' => 'bDelete= 0 and iArtType = 10'
//            ]);
//            foreach ($objArr as  $index => $obj) {
//                $imgArr = $this->getUnChangeImage($obj->mText);
//                if ($imgArr) {
//                    foreach ($imgArr as $img) {
//                        if (strpos($img,'http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest') !== false) {
//                            $arr = explode('/', $img);
//                            $fileName = end($arr);
//                            $filePath = TEMP_PATH .'/'. $fileName;
//                            file_put_contents($filePath, file_get_contents($img)); //写入缓存
//                            $url = Main::uploadFileToOSS($filePath,'other', 'SB201001');
//                            unlink($filePath);//删除图片
//                            if ($url) {
//                                $obj->mText = str_replace($img, $url, $obj->mText);
//                                if (!$obj->save()) {
//                                    echo '保存失败',json_encode(['iArtId' => $obj->iArtId]);
//                                    continue;
//                                }
//                            }
//                        } else {
//                            continue;
//                        }
//                    }
//                }
////                if ($img) {
////                    $imgArr = array_merge($imgArr, $img);
////                }
//            }
//            return $this->sendSuccessResponse('图片替换成功');
////            $imgArr = array_values(array_unique($imgArr)); //获取到不重复的文件
////            var_dump($imgArr);die;
////            $imgArr = array_values(array_filter(array_unique($imgArr),function ($val){
////                return strpos($val,'http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest') !== false;
////            })); //获取到不重复的文件
//////            var_dump($imgArr);die;
////            $replaceArr = [];
////            foreach ($imgArr as $fileUrl) {
////                $arr = explode('/', $fileUrl);
////                $fileName = end($arr);
////                $filePath = TEMP_PATH .'/'. $fileName;
////                file_put_contents($filePath, file_get_contents($fileUrl)); //写入缓存
////                $url = Main::uploadFileToOSS($filePath,'other', 'SB201001');
////                unlink($filePath);//删除图片
////                $replaceArr[$fileUrl] = $url;
////            }
////            foreach ($objArr as $index => $obj) {
////                $imgArr = $this->getUnChangeImage($obj->mText);
////                $imgArr = array_values(array_filter(array_unique($imgArr),function ($val){
////                    return strpos($val,'http://xuehaifile.oss-cn-hangzhou.aliyuncs.com/xhtest') !== false;
////                }));  //过滤
////                if ($imgArr) { //有图片需要替换
////                    foreach ($imgArr as $imgUrl) {
////                        if (isset($replaceArr[$imgUrl]) && $replaceArr[$imgUrl]) { //存在图片路径
////                            $obj->mText = str_replace($imgUrl, $replaceArr[$imgUrl], $obj->mText);
////                        }
////                    }
////                    if (!$obj->save()) {
////                        echo '保存失败',json_encode(['iArtId' => $obj->iArtId]);
////                        continue;
////                    }
////                }
////            }
////            echo json_encode($replaceArr);
//        } catch (\Exception $e) {
//            die($e->getMessage());
//        }
//    }

//    public function replaceCoverImgAction()
//    {
//        try {
//            $objArr = XhresArticlePub::find([
//                'conditions' => 'iArtId > 0'
//            ]);
//            foreach ($objArr as $obj) {
//                if ($obj->sCoverUrl) {
//                    if (strpos($obj->sCoverUrl,'/xhtest/') === false) {
//                        continue;
//                    } else {
//                        $arr = explode('/', $obj->sCoverUrl);
//                        $fileName = end($arr);
//                        $filePath = TEMP_PATH .'/'. $fileName;
//                        file_put_contents($filePath, file_get_contents($obj->sCoverUrl)); //写入缓存
//                        $url = Main::uploadFileToOSS($filePath,'other', 'SB201001');
//                        unlink($filePath);//删除图片
//                        if ($url) {
//                            $obj->sCoverUrl = $url;
//                            if (!$obj->save()) {
//                                echo '保存失败',json_encode(['iArtId' => $obj->iArtId]);
//                                continue;
//                            }
//                        }
//
//                    }
//                }
//            }
//            return $this->sendSuccessResponse('执行成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 获取未改变图片
     *
     * @param $str
     *
     * @return array
     *
     * create by dale  20180828
     */
//    function getUnChangeImage($str){
//        $reg = "/(href|src)=([\"|']?)([^\"'>]+.(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG))/i";
//        $matches = [];
//        preg_match_all($reg, $str, $matches);
//        $data = [];
//        foreach ($matches[3] as $row){
//            $data[] = $row;
//        }
//        return $data;
//    }

    /**
     * 封面图片替换
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180919
     */
//    public function replaceCoverAction()
//    {
//        try {
//            $objArr = XhresArticle::find([
//                'conditions' => 'bDelete= 0 and iArtType = 10'
//            ]);
//            foreach ($objArr as  $index => $row) {
//                $pub = XhresArticlePub::findFirst($row->iArtId);
//                if (!$pub) {
//                    continue;
//                }
//                $pub->sCoverUrl = '';
//                $pub->sCoverMobile = '';
//                if (!$pub->save()) {
//                    throw new XhException('保存失败');
//                }
////                $img = $this->getUnChangeImage($row->mText);
////                if ($img) {
////                    $pub = XhresArticlePub::findFirst($row->iArtId);
////                    if (!$pub) {
////                        continue;
////                    }
////                    $pub->sCoverUrl = Tool::getValue($img, 0 , '');
////                    $pub->sCoverMobile = Tool::getValue($img, 0 , '');
////                    if (!$pub->save()) {
////                        throw new XhException('保存失败');
////                    }
////                }
//            }
//            return $this->sendViewSuccess('封面添加成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//
//    }


//    function getImgs($str) {
//        $reg = '/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*(jpg|gif|png)/';
//        $matches = [];
//        preg_match_all($reg, $str, $matches);
//        $data = [];
//        foreach ($matches[0] as $row){
//            $data[] = $row;
//        }
//        return $data;
//    }

    /**
     * 活动不通过
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181031
     */
    public function activityUnpassAction()
    {
        try {
            $actArr = XhresArticle::find([
                'conditions' => 'bDelete= 0 and iArtType = 9 and iState = 3'
            ]);
            if ($actArr->toArray()) {
                $this->db->begin();
                foreach ($actArr as $act) {
                    if($act->iCreateUserId == $act->iLastModifyUserId && $act->iState == 3) {
                        $act->iState = 1;
                        if (!$act->save(null,null, false)) {
                            throw new XhException('修改失败');
                        }
                    }
                }
                $this->db->commit();
            }
            return $this->sendSuccessResponse('已将符合条件的不通过修改为待审核');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 页面
     *
     * create by sqb 20190110
     */
    public function statIndexAction()
    {
        $this->view->pick('article/stat');
        Assets::xhChart('js/article/stat.js');
        Assets::easyUI();
    }

    /**
     * 获取统计数据
     *
     * @return \Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190110
     */
    public function statAction()
    {
        $startTime1 = $this->request->getPost('startTime1');
        $startTime2 = $this->request->getPost('startTime2');
        $endTime1 = $this->request->getPost('endTime1');
        $endTime2 = $this->request->getPost('endTime2');
        $stat = XhresArticle::getData($startTime1, $startTime2, $endTime1, $endTime2);
        return $this->response->setJsonContent($stat);
    }

    /**
     * 导出
     *
     * @return bool|string
     * @throws XhException
     *
     * create by sqb 20190110
     */
    public function exportStatAction()
    {
        $this->view->disable();
        $title = ['语文', '数学', '英语', '科学', '其它'];
        $data = XhresArticle::getData();
        if (!$data) {
            return $this->sendViewError('无数据可导出');
        }

        Tool::exportExcelOnline('活动统计', $title, [$data['yList']]);
        return true;
    }
}
